import argparse

import requests
from vulnerability.database import CVEDatabase
from vulnerability.tracker import CVETracker
from vulnerability.call import create_pr, create_comment, make_body
from vulnerability.analysis import CommitQuery
import re

cve_db = CVEDatabase('fixed_commit_link')

def create_one_pr(cve_name, hw_email, id, branch, access_token, full_name_openeuler, head, commit_parameter, user_name, user_email, number):
    if(branch != "all" and branch not in cve_db.get_os_versions("all")):
        result = "无法识别的操作系统版本名称"
        #create_comment(commit_parameter, result)
        return

    if(branch != "all" and cve_db.check_os_version_is_openeuler(branch)):
        result = f"{branch}非内核分支，请使用 /create_pr {cve_db.get_os_parents(branch)}"
        create_comment(commit_parameter, result)
        return

    tracker = CVETracker(cve_db)
    print("Update cve commit for cve: ", cve_name)
    tracker.update_cve_commit(cve_name)
    result = {}
    return_message = {}
    hw_email = commit_parameter["hw_email"]
    id = commit_parameter["id"]
    print("Fix cve for branch: ", branch)
    code, push_branch = tracker.fix_cve(cve_name, branch, id, hw_email, number)
    return_message[push_branch] = ""
    if code == 0:
        parameter = {
                "access_token": access_token,
                "full_name": full_name_openeuler,
                "title": cve_name,
                "head": f"{head}:{push_branch}",
                "base": branch,
                "body": f"{hw_email}\n{cve_name}\n{return_message.get(push_branch, '')}\n\n" +
                       _get_issue_reference(cve_name)
                       ,
                "prune_source_branch": True,
            }
        try:
            response = create_pr(parameter)
            return_message[branch] = response.json()['html_url']
            print("第一次响应成功")
        except:
            print("第一次响应失败")
            response = create_pr(parameter)
            extra_message = response.json()['message']
            urls = re.findall(r'href="(https?://[^"]+)"', extra_message)
            if urls:
                    return_message[branch] = urls[0]
            else:
                return_message[branch] = extra_message
            

    result[branch] = tracker.get_fixed_result(code)
    if code == 0:
        result[branch] += return_message[branch]

    body = make_body(result, tracker)
    create_comment(commit_parameter, body)


def _get_issue_reference(cve_name):
    """获取关联的issue信息"""
    query = CommitQuery()
    commit_infos = query.get_commit_infos(cve_name)
    if not commit_infos:
        return ""
    
    issue_refs = []
    for info in commit_infos:
        if info.get('issue_number'):
            issue_refs.append(f"{cve_name}\nhttps://gitee.com/src-openeuler/kernel/issues/I{info['issue_number']}")
    
    return "\n\n".join(issue_refs) if issue_refs else ""

def _get_cve_details(cve_name):
    """获取CVE详细信息并格式化为字符串"""
    query = CommitQuery()
    cve_url = query.get_cve_url(cve_name)
    if not cve_url:
        return "CVE详情不可用"
    
    commit_infos = query.get_commit_infos(cve_name)
    if not commit_infos:
        return f"CVE详情页面: {cve_url}"
    
    details = ["CVE详情:"]
    details.append(f"URL: {cve_url}")
    details.append("\n提交信息:")
    
    for info in commit_infos:
        if info.get('introduced_version'):
            details.append(f"引入版本: {info['introduced_version']}")
            details.append(f"引入提交: {info['introduced_commit']}")
        if info.get('fixed_version'):
            details.append(f"修复版本: {info['fixed_version']}")
            details.append(f"修复提交: {info['fixed_commit']}")
        if info.get('issue_number'):
            details.append(f"关联Issue: #{info['issue_number']}")
        details.append("")
    
    return "\n".join(details)

def main():
    parser = argparse.ArgumentParser(description='创建CVE在指定分支下的修复补丁。')
    parser.add_argument('cve_name', type=str, help='CVE 名称，例如 CVE-2023-1234')
    parser.add_argument('hw_email', type=str, help='华为邮箱')
    parser.add_argument('id', type=str, help='ID')
    parser.add_argument('branch', type=str, help='分支名称，all为数据库中所有的openEuler分支')
    parser.add_argument('access_token', type=str)
    parser.add_argument('full_name', type=str)
    parser.add_argument('number', type=str)
    parser.add_argument('user_name', type=str)
    parser.add_argument('user_email', type=str)

    args = parser.parse_args()
    cve_name = str(args.cve_name).strip()
    hw_email = str(args.hw_email).strip()
    id = str(args.id).strip()
    branch = str(args.branch).strip()
    access_token = str(args.access_token).strip()
    full_name_srcopeneuler = str(args.full_name).strip()
    full_name_openeuler = "xiaocy1997/kernel"
    number = str(args.number).strip()
    head = "ci-robot/kernel"
    user_name = str(args.user_name).strip()
    user_email = str(args.user_email).strip()

    commit_parameter = {
        "access_token": access_token,
        "full_name": full_name_srcopeneuler,
        "number": number,
        "hw_email": hw_email,
        "id":id
    }

    if(branch == "all"):
        all_os_version = cve_db.get_os_versions(type='stable')
        for os_version in all_os_version:
            print("Create pr for branch: ", os_version)
            create_one_pr(cve_name, hw_email, id, os_version, access_token, full_name_openeuler, head, commit_parameter, user_name, user_email, number)
    else:
        print("Create pr for branch: ", branch)
        create_one_pr(cve_name, hw_email, id, branch, access_token, full_name_openeuler, head, commit_parameter, user_name, user_email, number)

    cve_db.close()


if __name__ == "__main__":
    result = main()
    